const mongoose = require('mongoose')
const dbconfig = require('./config')
const glob = require('glob')
const {resolve} = require('path')

const db = dbconfig.dbUrl+dbconfig.dbName
//需要将mongo的promis切换为nodejs的promise
mongoose.Promise = global.Promise

;(async ()=>{
    glob.sync(resolve(__dirname,'./schema/','**/*.js')).forEach(require)
})()

exports.connect = (()=>{
    //判断当前是否为生产环境
    let maxConnectTimes = 0;

    return new Promise((resolve,reject)=>{
        if(process.env.NODE_ENV !== 'production'){
            mongoose.set('debug',true)
        }
    
        //连接数据库
          mongoose.connect(db)
          let dbObj = mongoose.connection;
    
        //当连接断开
        dbObj.on('disconnect',()=>{
            maxConnectTimes++;
            if(maxConnectTimes<5){
                mongoose.connect(db)
            }else{
                throw new Error('数据库出现了问题')
            }
            
        })
    
        //当连接出错
        dbObj.on('error',err =>{
            maxConnectTimes++;
            if(maxConnectTimes<5){
                mongoose.connect(db)
            }else{
                reject(err);
                throw new Error('数据库出现了问题')
            }
        })
    
        //当连接打开
        dbObj.once('open',()=>{
            resolve(dbObj)
            console.log('MongoDB conneted seccessful！')
        })
    })
})()